package univ.bme.accounting.dao;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaQuery;

public abstract class GenericDAOImpl<T> implements GenericDAO<T>{

    @PersistenceContext
    protected EntityManager em;

    private Class<T> entityClass;

    protected GenericDAOImpl(Class<T> entityClass) {
    	this.entityClass = entityClass;
    }

    public void save(T entity) {
    	em.persist(entity);
    }

    protected void delete(Object id, Class<T> classe) {
    	T entityToBeRemoved = em.getReference(classe, id);
		em.remove(entityToBeRemoved);
    }

    public T update(T entity) {
    	return em.merge(entity);
    }

    public T find(int entityID) {
    	return em.find(entityClass, entityID);
    }

    // Using the unchecked because JPA does not have a
    // em.getCriteriaBuilder().createQuery()<T> method
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public List<T> findAll() {
		CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
		cq.select(cq.from(entityClass));
		return em.createQuery(cq).getResultList();
    }
}
